import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/order_detail.dart';
import 'package:fsharing/core/models/order_list.dart';
import 'package:fsharing/core/viewmodels/pages/mine/order/order_detail_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:provider/provider.dart';

/// 参数
class OrderDetailPageArgs {
  final int storeId;
  final String code;

  OrderDetailPageArgs(this.storeId, this.code);
}

/// 订单详情
class OrderDetailPage extends StatelessWidget {
  final OrderDetailPageArgs args;

  OrderDetailPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => OrderDetailModel(
        Provider.of(context, listen: false),
        args.storeId,
        args.code,
      ),
      child: BackgroundContainer(
        child: Scaffold(
          appBar: AppBar(
            leading: RoundBackButton(),
            title: Text('订单详情'),
          ),
          body: Consumer<OrderDetailModel>(
            builder: (context, model, child) {
              switch (model.viewState) {
                case ViewState.busy:
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                case ViewState.error:
                  return Center(
                    child: Text(model.errorMessage),
                  );
                case ViewState.success:
                  return _SuccessWidget(
                    orderDetail: model.orderDetail,
                  );
                default:
                  return Container();
              }
            },
          ),
        ),
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  final OrderDetail orderDetail;

  const _SuccessWidget({
    Key key,
    @required this.orderDetail,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 12),
      child: CustomScrollView(
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: _HeaderWidget(
              order: orderDetail.model,
            ),
          ),
          SliverFixedExtentList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return _ProductItemWidget(
                  product: orderDetail.model.orderDetails[index],
                );
              },
              childCount: orderDetail.model.orderDetails.length,
            ),
            itemExtent: 76,
          ),
          SliverToBoxAdapter(
            child: _FooterWidget(
              order: orderDetail.model,
            ),
          ),
          SliverToBoxAdapter(
            child: SizedBox(height: 12),
          ),
          SliverToBoxAdapter(
            child: _OrderInfoWidget(
              order: orderDetail.model,
            ),
          ),
          if (orderDetail.invoices.length > 0) ...[
            SliverToBoxAdapter(
              child: SizedBox(height: 12),
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  return _InvoiceItemWidget(
                    invoice: orderDetail.invoices[index],
                    isFirst: index == 0,
                    isLast: index == orderDetail.invoices.length - 1,
                  );
                },
                childCount: orderDetail.invoices.length,
              ),
            )
          ],
        ],
      ),
    );
  }
}

class _HeaderWidget extends StatelessWidget {
  final Order order;

  const _HeaderWidget({
    Key key,
    @required this.order,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/cart/img_store.png'),
          fit: BoxFit.fill,
        ),
      ),
      height: 45,
      child: Row(
        children: <Widget>[
          SizedBox(width: 12),
          Expanded(
            child: Text('${order.code}'),
          ),
        ],
      ),
    );
  }
}

class _ProductItemWidget extends StatelessWidget {
  final Product product;

  const _ProductItemWidget({
    Key key,
    @required this.product,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Row(
        children: <Widget>[
          SizedBox(width: 18),
          ClipRRect(
            borderRadius: BorderRadius.circular(3),
            child: CachedNetworkImage(
              imageUrl: product.productImage,
              width: 60,
              height: 60,
              fit: BoxFit.cover,
            ),
          ),
          SizedBox(width: 23),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  '${product.productName}',
                  style: TextStyle(color: Color(0xFF35353C), fontSize: 16),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/images/order/img_params.png'),
                      fit: BoxFit.fill,
                    ),
                  ),
                  width: 76,
                  height: 22,
                  child: Text('产品属性', style: TextStyle(fontSize: 14)),
                )
              ],
            ),
          ),
          Text(
            'x${product.quantity}',
            style: TextStyle(color: Color(0xFFAEAEAE), fontSize: 16),
          ),
          SizedBox(width: 30),
        ],
      ),
    );
  }
}

class _FooterWidget extends StatelessWidget {
  final Order order;

  const _FooterWidget({
    Key key,
    @required this.order,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var totalQuantity = 0;
    order.orderDetails.forEach((product) {
      totalQuantity += product.quantity;
    });
    var status = order.orderStatusStr;
    if (order.orderStatus == 'PAID') {
      if (order.deliveryStatus == 'CONFIRMING' || order.deliveryStatus == 'CONFIRMED') {
        status = order.deliveryStatusStr;
      }
    }
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/order/img_order_total.png'),
          fit: BoxFit.fill,
        ),
      ),
      height: 86,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          SizedBox(height: 6),
          Text(
            '共$totalQuantity件 | $status',
            style: TextStyle(color: Color(0xFF747474), fontSize: 13),
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: Text(
                  '运费：',
                  style: TextStyle(color: Color(0xFF747474)),
                ),
              ),
              Text(
                '￥${order.paidFreight ?? 0}',
                style: TextStyle(color: Color(0xFF747474)),
              ),
            ],
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: Text(
                  order.orderStatus == 'PAID' ? '实付款：' : '应付款：',
                  style: TextStyle(color: Color(0xFF747474)),
                ),
              ),
              Text.rich(
                TextSpan(
                  text: '￥',
                  style: TextStyle(color: Color(0xFFEA537A), fontSize: 15),
                  children: [
                    TextSpan(
                      text: '${order.paidAmount ?? 0}',
                      style: TextStyle(fontSize: 20),
                    ),
                  ],
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

class _InvoiceItemWidget extends StatelessWidget {
  final Invoice invoice;
  final bool isFirst;
  final bool isLast;

  _InvoiceItemWidget({
    Key key,
    @required this.invoice,
    @required this.isFirst,
    @required this.isLast,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: lightTheme(),
      child: Material(
        borderRadius: BorderRadius.vertical(
          top: isFirst ? Radius.circular(8) : Radius.zero,
          bottom: isLast ? Radius.circular(8) : Radius.zero,
        ),
        child: ListTile(
          title: Text(invoice.expressCompany),
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text('运单号：${invoice.expressNumber}'),
              Icon(Icons.keyboard_arrow_right),
            ],
          ),
          onTap: () {
            _onItemClicked(context);
          },
        ),
      ),
    );
  }

  void _onItemClicked(BuildContext context) {
    Navigator.of(context).pushNamed('/logistics', arguments: invoice);
  }
}

class _OrderInfoWidget extends StatelessWidget {
  final Order order;

  const _OrderInfoWidget({
    Key key,
    @required this.order,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
      ),
      height: 180,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Row(
            children: <Widget>[
              Image.asset(
                'assets/images/order/ic_line.png',
                width: 2,
              ),
              SizedBox(width: 6),
              Text(
                '订单信息',
                style: TextStyle(color: Colors.black),
              )
            ],
          ),
          Table(
            columnWidths: {0: FractionColumnWidth(.3)},
            children: [
              TableRow(
                children: [
                  _OrderInfoParamsWidget(
                    title: '订单编号：',
                  ),
                  Text(
                    order.code ?? '--',
                    style: TextStyle(color: Colors.grey),
                  ),
                ],
              ),
              TableRow(
                children: [
                  _OrderInfoParamsWidget(
                    title: '创建时间：',
                  ),
                  Text(
                    order.createTime ?? '--',
                    style: TextStyle(color: Colors.grey),
                  ),
                ],
              ),
              TableRow(
                children: [
                  _OrderInfoParamsWidget(
                    title: '付款时间：',
                  ),
                  Text(
                    order.payTime ?? '--',
                    style: TextStyle(color: Colors.grey),
                  ),
                ],
              ),
              if (order.deliveryStatus == 'CONFIRMING')
                TableRow(
                  children: [
                    _OrderInfoParamsWidget(
                      title: '发货时间：',
                    ),
                    Text(
                      order.deliveryTime ?? '',
                      style: TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
              if (order.deliveryStatus == 'CONFIRMED')
                TableRow(
                  children: [
                    _OrderInfoParamsWidget(
                      title: '收货时间：',
                    ),
                    Text(
                      order.deliveryTime ?? '',
                      style: TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
              TableRow(
                children: [
                  _OrderInfoParamsWidget(
                    title: '订单备忘：',
                  ),
                  Text(
                    order.memo ?? '--',
                    style: TextStyle(color: Colors.grey),
                  ),
                ],
              ),
            ],
          )
        ],
      ),
    );
  }
}

class _OrderInfoParamsWidget extends StatelessWidget {
  final String title;

  const _OrderInfoParamsWidget({
    Key key,
    @required this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 32,
      child: Text(
        title,
        style: TextStyle(color: Colors.black87),
      ),
    );
  }
}
